from datetime import datetime
from .. import db

class Task:
    def __init__(self, title, description, status='pending', priority=3, field_id=None, id=None, due_date=None, completed_at=None, task_type=None, created_by=None):
        self.id = id if id is not None else len(db.tasks) + 1
        self.title = title
        self.description = description
        self.status = status  # pending, in_progress, completed
        self.priority = priority  # 1: 高, 2: 中, 3: 低
        self.field_id = field_id
        self.task_type = task_type or 'general'  # 任务类型
        self.created_by = created_by  # 创建者ID
        self.created_at = datetime.utcnow()
        self.due_date = due_date
        self.completed_at = completed_at
    
    def save(self):
        """保存任务"""
        if not hasattr(self, 'id'):
            self.id = len(db.tasks) + 1
        if self not in db.tasks:
            db.tasks.append(self)
        return self
    
    @staticmethod
    def find_by_id(task_id):
        """通过ID查找任务"""
        for task in db.tasks:
            if task.id == int(task_id):
                return task
        return None
    
    @staticmethod
    def find_by_field(field_id):
        """查找农田相关的任务"""
        return [task for task in db.tasks if task.field_id == field_id]
    
    def update(self, data):
        """更新任务信息"""
        try:
            self.title = data.get('title', self.title)
            self.description = data.get('description', self.description)
            self.status = data.get('status', self.status)
            self.priority = data.get('priority', self.priority)
            self.field_id = data.get('field_id', self.field_id)
            self.task_type = data.get('task_type', self.task_type)
            
            if 'due_date' in data:
                self.due_date = datetime.fromisoformat(data['due_date'])
            
            if self.status == 'completed' and not self.completed_at:
                self.completed_at = datetime.utcnow()
            elif self.status != 'completed':
                self.completed_at = None
                
            return True
        except Exception as e:
            print(f"Error updating task: {str(e)}")
            return False
    
    def delete(self):
        """删除任务"""
        try:
            db.tasks.remove(self)
            return True
        except Exception as e:
            print(f"Error deleting task: {str(e)}")
            return False
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'status': self.status,
            'priority': self.priority,
            'field_id': self.field_id,
            'task_type': self.task_type,
            'created_by': self.created_by,
            'created_at': self.created_at.isoformat(),
            'due_date': self.due_date.isoformat() if self.due_date else None,
            'completed_at': self.completed_at.isoformat() if self.completed_at else None
        } 